<?php
/**
 * 模型逻辑处理
 */

namespace plugins\qbt_custom_model\service;

use think\Config;
use think\Db;

class ModelService
{
    /**
     * 处理模型添加工作
     * @param array $data
     * @return bool
     */
    public static function addModel($data = [])
    {
        if (empty($data)) return false;

        // 修复使用已有表情况缺少字段问题
        $data['is_default_field'] = isset($data['is_default_field'])?$data['is_default_field']:1;

        //$last_id = self::addMenu($data);
        $config = Config::get('database');
        $data['model_tabname'] = str_replace($config['prefix'], '', $data['model_tabname']);
        $model_data = [
            'model_name' => $data['model_name'],
            'model_tabname' => $data['model_tabname'],
            //'model_app' => $data['model_app'],
            'model_controller' => $data['model_controller'],
            //'model_menu' => $data['model_menu'],
            'model_description' => $data['model_description'],
            //'model_ico' => $data['model_ico'],
            'model_status' => $data['model_status'],
            'distinguish' => $data['distinguish'],
            'is_default_field' => $data['is_default_field'],
            //'menu_id' => $last_id,
            'addtime' => time(),
        ];
        //开始添加模型
        $lastid = Db::name('model')->insertGetId($model_data);
        #nsh 20190107 修改
        if ($lastid !== false) {
            if ($data['is_default_field'] == 1) {
                if ($data['type'] == 2) {
                    $datas = self::existence_model($lastid,$data,$config);
                } else {
                    $datas = self::add_default_model($lastid,$data);
                }
                Db::name('model_field')->insertAll($datas);
            }
            return $lastid; // edit by 曾镇楚 2019-01-29 将返回值由true 改为  $lastid，方便后续操作
        } else {
            return false;
        }
    }

    /**
     * 添加菜单
     * @param $data
     */
    /*private static function addMenu($data){
        $data_arr = [
            'parent_id' => $data['model_menu'],
            'name' => $data['model_name'],
            'app' => $data['model_app'],
            'controller' => $data['model_controller'],
            'action' => 'index',
            'icon' => $data['model_ico'],
            'status' => 1,
            'type' => 1
        ];
        $admin_menu = Db::name('AdminMenu');
        $res = $admin_menu->strict(false)->field(true)->insert($data_arr);
        $last_id = $admin_menu->getLastInsID();

        $authRuleName = $data['model_app']."/".$data['model_controller']."/index";
        $findAuthRuleCount = Db::name('auth_rule')->where([
            'app'  => $data['model_app'],
            'name' => $authRuleName,
            'type' => 'admin_url'
        ])->count();
        if (empty($findAuthRuleCount)) {
            Db::name('AuthRule')->insert([
                "name"  => $authRuleName,
                "app"   => $data['model_app'],
                "type"  => "admin_url", //type 1-admin rule;2-user rule
                "title" => $data['model_name'],
                'param' => "",
            ]);
        }

        cache(null, 'admin_menus');// 删除后台菜单缓存
        if($res){
            return $last_id;
        }else{
            return 0;
        }
    }*/

    /**
     * 编辑模型
     */
    public static function editModel($data)
    {
        if (empty($data)) return false;
        //$last_id = self::editMenu($data);
        $model_data = [
            'model_id' => $data['model_id'],
            'model_name' => $data['model_name'],
            'model_tabname' => $data['model_tabname'],
            //'model_app' => $data['model_app'],
            'model_controller' => $data['model_controller'],
            //'model_menu' => $data['model_menu'],
            'model_description' => $data['model_description'],
            //'model_ico' => $data['model_ico'],
            'model_status' => $data['model_status']
        ];
        //开始添加模型
        $res = Db::name('model')->where(['model_id' => $data['model_id']])->update($model_data);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成控制器
     */
    public static function create_controller($app = "", $cname = "", $model = "")
    {

    }

    /**
     * 生成模版
     */
    public static function create_template()
    {

    }

    public static  function existence_model($lastid,$data,$config){
        $pk = Db::name($data['model_tabname'])->getPk();
        if (empty($pk)) {
            #如没有主键，则建立主键
            Db::execute('ALTER TABLE   ' . $config['prefix'] . $data['model_tabname'] . ' ADD id ADD(10) unsigned NOT NULL AUTO_INCREMENT primary key');
        }
        $data_menu = Db::name($data['model_tabname'])->getTableFields();
        if ($data['distinguish'] == 1 && !in_array('parent_id', $data_menu)) {
            $data_menu[] = 'parent_id';
            Db::execute('ALTER TABLE ' . $config['prefix'] . $data['model_tabname'] . ' ADD parent_id ADD(8) NOT NULL  DEFAULT 0');
//                   ; # 分类模型 默认添加
        }
        $datas = [];
        foreach ($data_menu as $k => $item_menu) {
            if ($item_menu !== $pk) {
                $data_menu_op['field_name'] = $item_menu;
                $data_menu_op['model_id'] = $lastid;
                $data_menu_op['field_nikename'] = '默认标题';
                $data_menu_op['field_type'] = 'text';
                $data_menu_op['field_type2'] = 'varchar';
                $data_menu_op['field_length'] = 255;
                $data_menu_op['field_status'] = 1;
                $data_menu_op['field_is_default'] = 0;
                $data_menu_op['field_add_show'] = 1;
                $data_menu_op['field_default'] = '';
                $data_menu_op['field_choose'] = '';
                $data_menu_op['field_is_index'] = 1;
                $data_menu_op['field_sort'] = 10 * $k;
                $data_menu_op['field_edit_show'] = 1;
                $data_menu_op['field_add_edit_show_many_column'] = 1;
                $datas[] = $data_menu_op;
            }
        }
        return true;
    }

    public static function add_default_model($lastid,$data){
        if ($data['distinguish'] == 1) {
            $datas = [
                ['model_id' => $lastid, 'field_name' => 'title', 'field_nikename' => '标题', 'field_type' => 'text', 'field_type2' => 'varchar', 'field_length' => 255, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 1, 'field_sort' => '10', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],

                ['model_id' => $lastid, 'field_name' => 'status', 'field_nikename' => '状态', 'field_type' => 'select', 'field_type2' => 'tinyint', 'field_length' => 1, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 1, 'field_default' => '1', 'field_choose' => "1=关闭\r\n2=显示", 'field_is_index' => 1, 'field_sort' => '20', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 1],

                ['model_id' => $lastid, 'field_name' => 'listorder', 'field_nikename' => '排序', 'field_type' => 'number', 'field_type2' => 'int', 'field_length' => 10, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '30', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 1],

                ['model_id' => $lastid, 'field_name' => 'create_time', 'field_nikename' => '创建时间', 'field_type' => 'datetime', 'field_type2' => 'int', 'field_length' => 10, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 0, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 1, 'field_sort' => '40', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],

                ['model_id' => $lastid, 'field_name' => 'update_time', 'field_nikename' => '更新时间', 'field_type' => 'datetime', 'field_type2' => 'int', 'field_length' => 10, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 0, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 1, 'field_sort' => '50', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],

                ['model_id' => $lastid, 'field_name' => 'seo_title', 'field_nikename' => 'seo标题', 'field_type' => 'textarea', 'field_type2' => 'longtext', 'field_length' => 10000, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '60', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],

                ['model_id' => $lastid, 'field_name' => 'seo_description', 'field_nikename' => 'seo内容', 'field_type' => 'select', 'field_type2' => 'tinyint', 'field_length' => 1, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '0', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '70', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],

                ['model_id' => $lastid, 'field_name' => 'seo_keywords', 'field_nikename' => 'seo关键字', 'field_type' => 'textarea', 'field_type2' => 'text', 'field_length' => 0, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '0', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '80', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],

                ['model_id' => $lastid, 'field_name' => 'parent_id', 'field_nikename' => '父级id', 'field_type' => 'number', 'field_type2' => 'int', 'field_length' => 11, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '90', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],
            ];
        } elseif ($data['distinguish'] == 2) {
            $datas = [
                ['model_id' => $lastid, 'field_name' => 'title', 'field_nikename' => '标题', 'field_type' => 'text', 'field_type2' => 'varchar', 'field_length' => 255, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 1, 'field_sort' => '10', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],
                ['model_id' => $lastid, 'field_name' => 'status', 'field_nikename' => '状态', 'field_type' => 'select', 'field_type2' => 'tinyint', 'field_length' => 1, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 1, 'field_default' => '1', 'field_choose' => "1=关闭\r\n2=显示", 'field_is_index' => 1, 'field_sort' => '20', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 1],
                ['model_id' => $lastid, 'field_name' => 'listorder', 'field_nikename' => '排序', 'field_type' => 'number', 'field_type2' => 'int', 'field_length' => 10, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '30', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 1],
                ['model_id' => $lastid, 'field_name' => 'create_time', 'field_nikename' => '创建时间', 'field_type' => 'datetime', 'field_type2' => 'int', 'field_length' => 10, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 0, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 1, 'field_sort' => '40', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],
                ['model_id' => $lastid, 'field_name' => 'update_time', 'field_nikename' => '更新时间', 'field_type' => 'datetime', 'field_type2' => 'int', 'field_length' => 10, 'field_status' => 1, 'field_is_default' => 1, 'field_add_show' => 0, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 1, 'field_sort' => '50', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],
                ['model_id' => $lastid, 'field_name' => 'published_time', 'field_nikename' => '发布时间', 'field_type' => 'datetime', 'field_type2' => 'int', 'field_length' => 10, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '60', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 1],
                ['model_id' => $lastid, 'field_name' => 'is_top', 'field_nikename' => '置顶', 'field_type' => 'select', 'field_type2' => 'tinyint', 'field_length' => 1, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '0', 'field_choose' => "1=不置顶\r\n2=置顶", 'field_is_index' => 0, 'field_sort' => '70', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 1],
                ['model_id' => $lastid, 'field_name' => 'recomment', 'field_nikename' => '推荐', 'field_type' => 'select', 'field_type2' => 'tinyint', 'field_length' => 1, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '0', 'field_choose' => "1=不推荐\r\n2=推荐", 'field_is_index' => 0, 'field_sort' => '80', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 1],
                ['model_id' => $lastid, 'field_name' => 'content', 'field_nikename' => '内容', 'field_type' => 'html', 'field_type2' => '', 'field_length' => 10000, 'field_status' => 1, 'field_is_default' => 0, 'field_add_show' => 1, 'field_default' => '', 'field_choose' => '', 'field_is_index' => 0, 'field_sort' => '90', 'field_edit_show' => 1, 'field_add_edit_show_many_column' => 0],
            ];
        }
        return $datas;
    }

}